<?php
/**
 * Created by PhpStorm.
 * Date: 2021/1/25
 * Time: 11:29 AM
 */
namespace app\admin\controller;

use app\admin\validate\ChannelValidate;
use think\exception\ValidateException;
use think\facade\View;

class Channel extends Base
{
    // 栏目列表
    public function index()
    {
        if (request()->isAjax()) {

            $channelModel = new \app\admin\model\Channel();
            $channelList = $channelModel->getChannelList()['data'];

            $channelType = config('xcms.channel_type');
            $modelxModel = new \app\admin\model\Modelx();
            $modelInfo = $modelxModel->getAllModelx()['data'];
            $modelMap = [];
            foreach ($modelInfo as $vo) {
                $modelMap[$vo['model_id']] = $vo['name'];
            }

            foreach ($channelList as $key => $vo) {
                $channelList[$key]['type_name'] = $channelType[$vo['type']];
                $channelList[$key]['model_name'] = $modelMap[$vo['model_id']];

                if ($vo['type'] == 'link') {
                    $channelList[$key]['url'] = $vo['outlink'];
                } else {
                    $channelList[$key]['url'] = '/c/' . $vo['diyname'];
                }
            }

            return json(['code' => 0, 'data' => $channelList, 'msg' => 'success']);
        }

        return View::fetch();
    }

    // 添加栏目
    public function add()
    {
        $channelModel = new \app\admin\model\Channel();

        if (request()->isPost()) {

            $param = input('post.');

            // 基础校验
            try {

                validate(ChannelValidate::class)->check($param);
            } catch (ValidateException $e) {

                return json(['code' => -1, 'data' => [], 'msg' => $e->getError()]);
            }

            // 业务逻辑校验
            $res = $this->checkParam($param);
            if (0 != $res['code']) {
                return json($res);
            }

            $res = $channelModel->addChannel([
                'type' => $param['type'],
                'model_id' => $param['model_id'],
                'parent_id' => $param['selTree1_select_nodeId'],
                'name' => $param['name'],
                'image' => $param['image'],
                'seo_title' => $param['seo_title'],
                'keywords' => $param['keywords'],
                'description' => $param['description'],
                'diyname' => $param['diyname'],
                'outlink' => $param['outlink'],
                'channel_tpl' => $param['channel_tpl'],
                'list_tpl' => $param['list_tpl'],
                'show_tpl' => $param['show_tpl'],
                'pagesize' => $param['pagesize'],
                'status' => $param['status'],
                'create_time' => date('Y-m-d H:i:s')
            ]);

            return json($res);
        }

        $pid = input('param.pid');
        // 模型信息
        $modelxModel = new \app\admin\model\Modelx();
        $modelInfo = $modelxModel->getAllModelx()['data'];
        $model = [];
        $modeIdTpl = [];
        foreach ($modelInfo as $key => $vo) {
            $model[$vo['model_id']] = $vo['name'];
            $modeIdTpl[$vo['model_id']] = [
                'channel_tpl' => $vo['channel_tpl'],
                'list_tpl' => $vo['list_tpl'],
                'show_tpl' => $vo['show_tpl']
            ];
        }

        // 栏目树
        $channelList = $channelModel->getAllChannelTree()['data'];
        $channelList = makeMenuTree($channelList);
        $channelTree = [
            'title' => '顶级栏目',
            'id' => 0,
            'parentId' => 0,
            'children' => $channelList
        ];

        View::assign([
            'channel_type' => config('xcms.channel_type'),
            'model' => $model,
            'model_tpl' => json_encode($modeIdTpl),
            'pid' => $pid,
            'channel_tree' => json_encode($channelTree),
            'img' => config('images')
        ]);

        return View::fetch();
    }

    // 设置栏目状态
    public function setChannelStatus()
    {
        if (request()->isAjax()) {

            $channelId = input('param.id');
            $status = input('param.status');

            $channelModel = new \app\admin\model\Channel();
            $res = $channelModel->updateChannelStatus([
                'channel_id' => $channelId,
                'status' => $status
            ]);

            return json($res);
        }
    }

    // 编辑栏目
    public function edit()
    {
        $channelModel = new \app\admin\model\Channel();

        if (request()->isPost()) {

            $param = input('post.');

            // 基础校验
            try {

                validate(ChannelValidate::class)->check($param);
            } catch (ValidateException $e) {

                return json(['code' => -1, 'data' => [], 'msg' => $e->getError()]);
            }

            // 业务逻辑校验
            $res = $this->checkParam($param);
            if (0 != $res['code']) {
                return json($res);
            }

            $res = $channelModel->editChannel([
                'channel_id' => $param['channel_id'],
                'type' => $param['type'],
                'model_id' => $param['model_id'],
                'parent_id' => $param['selTree1_select_nodeId'],
                'name' => $param['name'],
                'image' => $param['image'],
                'seo_title' => $param['seo_title'],
                'keywords' => $param['keywords'],
                'description' => $param['description'],
                'diyname' => $param['diyname'],
                'outlink' => $param['outlink'],
                'channel_tpl' => $param['channel_tpl'],
                'list_tpl' => $param['list_tpl'],
                'show_tpl' => $param['show_tpl'],
                'pagesize' => $param['pagesize'],
                'status' => $param['status'],
                'update_time' => date('Y-m-d H:i:s')
            ]);

            return json($res);
        }

        $channelId = input('param.id');
        $info = $channelModel->getChannelById($channelId)['data'];

        $pid = $info['parent_id'];
        // 模型信息
        $modelxModel = new \app\admin\model\Modelx();
        $modelInfo = $modelxModel->getAllModelx()['data'];
        $model = [];
        $modeIdTpl = [];
        foreach ($modelInfo as $key => $vo) {
            $model[$vo['model_id']] = $vo['name'];
            $modeIdTpl[$vo['model_id']] = [
                'channel_tpl' => $vo['channel_tpl'],
                'list_tpl' => $vo['list_tpl'],
                'show_tpl' => $vo['show_tpl']
            ];
        }

        // 栏目树
        $channelList = $channelModel->getAllChannelTree()['data'];
        $channelList = makeMenuTree($channelList);
        $channelTree = [
            'title' => '顶级栏目',
            'id' => 0,
            'parentId' => 0,
            'children' => $channelList
        ];

        View::assign([
            'channel_type' => config('xcms.channel_type'),
            'model' => $model,
            'model_tpl' => json_encode($modeIdTpl),
            'pid' => $pid,
            'channel_tree' => json_encode($channelTree),
            'img' => config('images'),
            'info' => $info
        ]);

        return View::fetch();
    }

    // 删除栏目
    public function del()
    {
        if (request()->isAjax()) {

            $channelId = input('param.id');

            $channelModel = new \app\admin\model\Channel();
            $res = $channelModel->delChannelById($channelId);

            return json($res);
        }
    }

    /**
     * 检测参数
     * @param $param
     * @return array
     */
    private function checkParam(&$param)
    {
        if ('list' == $param['type']) {

            unset($param['channel_tpl']);

            if (empty($param['list_tpl'])) {
                return ['code' => -2, 'data' => [], 'msg' => '列表页模板不能为空'];
            }

            if (empty($param['show_tpl'])) {
                return ['code' => -3, 'data' => [], 'msg' => '详情页模板不能为空'];
            }

            $res = checkTplFormat($param);
            if (0 != $res['code']) {
                return $res;
            }

            if (empty($param['pagesize'])) {
                return ['code' => -4, 'data' => [], 'msg' => '分页大小不能为空'];
            }

            $param['channel_tpl'] = '';
        } else if ('channel' == $param['type']) {

            unset($param['list_tpl'], $param['show_tpl']);

            if (empty($param['channel_tpl'])) {
                return ['code' => -3, 'data' => [], 'msg' => '栏目页模板不能为空'];
            }

            $res = checkTplFormat($param);
            if (0 != $res['code']) {
                return $res;
            }

            $param['list_tpl'] = '';
            $param['show_tpl'] = '';
        } else if ('link' == $param['type']) {

            $param['channel_tpl'] = '';
            $param['list_tpl'] = '';
            $param['show_tpl'] = '';

            if (empty($param['outlink'])) {
                return ['code' => -3, 'data' => [], 'msg' => '外部链接不能为空'];
            }

            if (strpos($param['outlink'], 'http://') === false &&
                strpos($param['outlink'], 'https://') === false) {
                return ['code' => -4, 'data' => [], 'msg' => '外部链接必须以http://或者https://开头'];
            }
        }

        return ['code' => 0, 'data' => [], 'msg' => 'ok'];
    }
}